import { MockMethod } from 'vite-plugin-mock'
import { error, success } from './helper'

const tokens = {
  admin: 'admin-token',
  editor: 'editor-token'
}

const users = {
  'admin-token': {
    id: 1,
    name: 'Admin',
    avatar: 'https://avatars.githubusercontent.com/u/1?v=4',
    roles: ['admin'],
    permissions: ['*']
  },
  'editor-token': {
    id: 2,
    name: 'Editor',
    avatar: 'https://avatars.githubusercontent.com/u/2?v=4',
    roles: ['editor'],
    permissions: ['view', 'edit']
  }
}

export default [
  {
    url: '/api/user/login',
    method: 'post',
    response: ({ body }) => {
      const { username } = body
      const token = tokens[username]

      if (!token) {
        return error(401, '用户名或密码错误')
      }

      return success(
        {
          token
        },
        '登录成功'
      )
    }
  },
  {
    url: '/api/user/info',
    method: 'get',
    response: ({ headers }) => {
      const token = headers['authorization']?.replace('Bearer ', '')
      const userInfo = users[token]

      if (!userInfo) {
        return error(401, 'Token 无效')
      }

      return success(userInfo)
    }
  },
  {
    url: '/api/user/logout',
    method: 'post',
    response: () => {
      return success(null, '退出成功')
    }
  }
] as MockMethod[]
